package org.dromara.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.SysXzqh;
import org.dromara.system.domain.bo.SysXzqhBo;
import org.dromara.system.domain.vo.SysXzqhVo;
import org.dromara.system.mapper.SysXzqhMapper;
import org.dromara.system.service.ISysXzqhService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 行政区划Service业务层处理
 *
 * @author Chen
 * @date 2024-02-26
 */
@RequiredArgsConstructor
@Service
public class SysXzqhServiceImpl implements ISysXzqhService {

    private final SysXzqhMapper baseMapper;

    /**
     * 查询行政区划
     */
    @Override
    public SysXzqhVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }


    /**
     * 查询行政区划列表
     */
    @Override
    public List<SysXzqhVo> queryList(SysXzqhBo bo) {
        LambdaQueryWrapper<SysXzqh> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysXzqh> buildQueryWrapper(SysXzqhBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysXzqh> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getName()), SysXzqh::getName, bo.getName());
        lqw.like(bo.getCode()!=null, SysXzqh::getExtId, bo.getCode());
        lqw.orderByAsc(SysXzqh::getId);
        return lqw;
    }

    /**
     * 新增行政区划
     */
    @Override
    public Boolean insertByBo(SysXzqhBo bo) {
        SysXzqh add = BeanUtil.toBean(bo, SysXzqh.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;

        return flag;
    }

    /**
     * 修改行政区划
     */
    @Override
    public Boolean updateByBo(SysXzqhBo bo) {
        SysXzqh update = BeanUtil.toBean(bo, SysXzqh.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysXzqh entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除行政区划
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


}
